from functools import wraps
from flask import jsonify
from utils import setup_logger
from utils.code import ErrorCode

class ErrorHandler:
    def __init__(self):
        self.logger = setup_logger()

    def log_exception(self, error_code):
        self.logger.error(f"Error occurred: {error_code.message} (Code: {error_code.code})")

    def handle_exception(self, error_code):
        self.log_exception(error_code)
        return jsonify(error_code.to_dict()), error_code.code

    def catch_exceptions(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except ValueError:
                return self.handle_exception(ErrorCode.INVALID_INPUT)
            except KeyError:
                return self.handle_exception(ErrorCode.NOT_FOUND)
            except Exception as e:
                self.logger.exception("An unexpected error occurred")
                return self.handle_exception(ErrorCode.INTERNAL_ERROR)
        return wrapper
